//
//  ZHUserAccountViewModel.swift
//  weibosina
//
//  Created by zhangzhen on 16/6/17.
//  Copyright © 2016年 zhangzhen. All rights reserved.
//

import UIKit

/// 用户的视图模型
class ZHUserAccountViewModel {
    //创建一个单例
    static let shareUserAccount = ZHUserAccountViewModel()
    ///用户模型
    var userAccount : ZHUserAccount?
    /// 返回有效的token
    var accessToken : String?{
        
        if  !isExpired{
            //没过期,返回对应的access_token
            return userAccount?.access_token
        }
        return nil
    }
    
    /// 计算过期时间
    var isExpired : Bool{
        if userAccount?.expiresDate?.compare(NSDate())==NSComparisonResult.OrderedDescending{
            //如果是降序,
            return false
        }
        //过期返回true
        return true
            
        
    }
    //用户登录的标记,没过期,并且有access_token
    var userLogin: Bool {
        return !isExpired && (userAccount?.access_token != nil)
    }
    
    /// 如果在 OC 中，可以通过只读属性／函数的方式实现,保存的路径
    private var accountPath: String {
        
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    private init(){
        
        //在加载视图模型的时候从沙盒中解档
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? ZHUserAccount
        //判断模型中的过期属性
        if isExpired{
            print("已经过期")
            userAccount == nil
        }
        
    }
    
    

}


extension ZHUserAccountViewModel{
    //用模型中的数据去请求数据
    func loadAccessToken(code: String,finished:(isSuccessed: Bool)->()) {
        
        ZHNetWorkTools.sharetools.loadAccessToken(code) { (result, error) in
            if error != nil {
                print("出错了")
                finished(isSuccessed: false)
                return
            }
            //将请求的结果转化为模型
            self.userAccount = ZHUserAccount(dict: result as![String : AnyObject])
            self.userAccount!.access_token = "2.00Pa7upFjhmgTD00048eb2b60HALbn"
           
           //请求到的信息进行获取用户信息
            self.loadUserInfo(self.userAccount!, finished: finished)
            
        }
    }
    
    
    private func loadUserInfo(account: ZHUserAccount, finished: (isSuccessed: Bool)->()) {
        
        ZHNetWorkTools.sharetools.loadUserInfo(account.uid!, finished: { (result, error) in
            if error != nil {
                
                print("加载用户出错了")
                
                finished(isSuccessed: false)
                return
            }
            //判断一定有内容,并且是字典
                guard let dict = result as? [String:AnyObject] else{
                    print("格式有误")
                    //返回错误,拿到的result不对
                    finished(isSuccessed: false)
                    return
                }

                // 将用户信息保存
                account.screen_name = dict["screen_name"] as? String
                account.avatar_large = dict["avatar_large"] as? String
            
                //归档,保存到沙盒
                NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
                
                print(self.accountPath)
                
                // 需要完成回调!!!
                finished(isSuccessed: true)
                
            
        })

        
    }
    
    
}

